package net.blank.functionUtl
{
	import flash.utils.Dictionary;
	import flash.utils.Proxy;
	import flash.utils.flash_proxy;
	
	/**
	 * 通过代理观察对象的属性改变或方法被调用
	 * @author blank
	 * 
	 */
	public class ProxyWatcher extends Proxy
	{
		/**
		 * 被观察的对象
		 */
		private var _target:Object;
		
		/**
		 * 被观察的属性列表
		 */
		private var properties:Dictionary;
		
		/**
		 * 被观察的方法列表
		 */
		private var calles:Dictionary;
		
		/**
		 * 通过代理观察对象的属性改变或方法被调用
		 * @param target
		 * 
		 */
		public function ProxyWatcher(target:*){
			_target=target;
			
			properties=new Dictionary();
			
			calles=new Dictionary();
		}
		
		/**
		 * 观察属性改变
		 * @param propertyName
		 * @param callBackFunc
		 * 
		 */
		public function watchProperty(propertyName:String,callBackFunc:Function):void{
			if(!(propertyName in properties)){
				properties[propertyName]=callBackFunc;
			}
		}
		
		/**
		 * 观察方法被执行
		 * @param callName
		 * @param callBackFunc
		 * 
		 */
		public function watchCall(callName:String,callBackFunc:Function):void{
			if(!(callName in calles)){
				calles[callName]=callBackFunc;
			}
		}
		
		override flash_proxy function setProperty(name:*, value:*):void{
			var propertyName:String=String(name);
			
			if(propertyName in properties){
				if(value != _target[propertyName]){
					if(properties[propertyName].apply(_target,[value])){
						_target[propertyName]=value;
					}
				}
			}else{
				_target[propertyName]=value;
			}
		}
		
		override flash_proxy function getProperty(name:*):*{
			return _target[name];
		}
		
		override flash_proxy function callProperty(name:*, ...parameters):*{
			var callName:String=String(name);
			
			if(callName in calles){
				if(calles[callName].apply(_target,[parameters])){
					return _target[callName].apply(_target,parameters);
				}
			}else{
				return _target[callName].apply(_target,parameters);
			}
		}
	}
}